// 测试SQL解析功能
const testSql = `
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '用户ID',
    username VARCHAR(50) NOT NULL UNIQUE COMMENT '用户名',
    email VARCHAR(100) NOT NULL UNIQUE COMMENT '邮箱地址',
    password VARCHAR(255) NOT NULL COMMENT '密码',
    nickname VARCHAR(100) COMMENT '昵称',
    avatar VARCHAR(500) COMMENT '头像URL',
    phone VARCHAR(20) COMMENT '手机号',
    status TINYINT DEFAULT 1 COMMENT '状态：1-正常，0-禁用',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
);
`;

// 模拟解析函数
function parseSqlCreateTable(sql) {
  const fields = []
  
  try {
    // 清理 SQL 语句，移除多余的空白字符和注释
    let cleanSql = sql.replace(/--.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '').trim()
    
    // 提取表定义部分
    const tableMatch = cleanSql.match(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?(\w+)`?\s*\(([\s\S]*)\)/i)
    if (!tableMatch) {
      throw new Error('无法识别 CREATE TABLE 语句格式')
    }

    const tableDefinition = tableMatch[2]
    
    // 分割字段定义，处理括号内的内容
    const fieldDefinitions = splitFieldDefinitions(tableDefinition)
    
    fieldDefinitions.forEach((fieldDef, index) => {
      const field = parseFieldDefinition(fieldDef.trim())
      if (field) {
        fields.push(field)
      }
    })
    
  } catch (error) {
    throw new Error(`SQL 解析失败: ${error.message}`)
  }
  
  return fields
}

function splitFieldDefinitions(definition) {
  const fields = []
  let current = ''
  let parenthesesCount = 0
  let inQuotes = false
  let quoteChar = ''
  
  for (let i = 0; i < definition.length; i++) {
    const char = definition[i]
    
    if (!inQuotes && (char === '"' || char === "'" || char === '`')) {
      inQuotes = true
      quoteChar = char
    } else if (inQuotes && char === quoteChar) {
      inQuotes = false
      quoteChar = ''
    } else if (!inQuotes) {
      if (char === '(') {
        parenthesesCount++
      } else if (char === ')') {
        parenthesesCount--
      } else if (char === ',' && parenthesesCount === 0) {
        if (current.trim()) {
          fields.push(current.trim())
        }
        current = ''
        continue
      }
    }
    
    current += char
  }
  
  if (current.trim()) {
    fields.push(current.trim())
  }
  
  return fields.filter(field => 
    !field.match(/^\s*(PRIMARY\s+KEY|FOREIGN\s+KEY|KEY|INDEX|UNIQUE\s+KEY|CONSTRAINT)/i)
  )
}

function parseFieldDefinition(fieldDef) {
  try {
    // 匹配字段定义的各个部分
    const fieldMatch = fieldDef.match(/^`?(\w+)`?\s+(\w+)(?:\(([^)]+)\))?\s*(.*)/i)
    if (!fieldMatch) {
      return null
    }

    const [, columnName, sqlType, typeParams, constraints] = fieldMatch
    
    // 转换数据类型
    const dataType = mapSqlTypeToDataType(sqlType, typeParams)
    
    // 检查是否必填
    const isRequired = /NOT\s+NULL/i.test(constraints) ? 1 : -1
    
    // 检查是否唯一
    const isUnique = /UNIQUE/i.test(constraints) ? 1 : 0
    
    // 提取默认值
    let defaultValue = ''
    const defaultMatch = constraints.match(/DEFAULT\s+([^,\s]+)/i)
    if (defaultMatch) {
      defaultValue = defaultMatch[1].replace(/['"]/g, '')
    }
    
    // 提取注释
    let comment = ''
    const commentMatch = constraints.match(/COMMENT\s+['"](.*?)['"]/i)
    if (commentMatch) {
      comment = commentMatch[1]
    }
    
    // 生成显示名称（将下划线转换为空格并首字母大写）
    const displayName = columnName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
    
    // 生成 Java 变量名（驼峰命名）
    const javaName = columnName.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase())
    
    return {
      name: displayName,
      javaName: javaName,
      columnName: columnName,
      dataType: dataType,
      required: isRequired,
      unique: isUnique,
      defaultValue: defaultValue,
      comment: comment
    }
  } catch (error) {
    console.error('解析字段定义失败:', fieldDef, error)
    return null
  }
}

function mapSqlTypeToDataType(sqlType, typeParams) {
  const type = sqlType.toUpperCase()
  
  switch (type) {
    case 'VARCHAR':
    case 'CHAR':
    case 'TEXT':
    case 'LONGTEXT':
    case 'MEDIUMTEXT':
    case 'TINYTEXT':
      return 1 // 字符串
    case 'INT':
    case 'INTEGER':
    case 'BIGINT':
    case 'SMALLINT':
    case 'TINYINT':
      return 2 // 整数
    case 'DECIMAL':
    case 'NUMERIC':
    case 'FLOAT':
    case 'DOUBLE':
      return 5 // 浮点数
    case 'BOOLEAN':
    case 'BOOL':
      return 6 // 布尔值
    case 'DATE':
      return 9 // 日期
    case 'DATETIME':
    case 'TIMESTAMP':
      return 8 // 时间戳
    case 'JSON':
      return 17 // JSON
    default:
      return 1 // 默认为字符串
  }
}

// 运行测试
try {
  const result = parseSqlCreateTable(testSql)
  console.log('解析结果:', JSON.stringify(result, null, 2))
  console.log('测试通过！解析了', result.length, '个字段')
} catch (error) {
  console.error('测试失败:', error.message)
} 